#!/bin/sh

. /etc/rc.conf
. /etc/rc.d/functions

ADDRESS='127.0.0.1:8000'
PROJECTDIR="/srv/http/django/sample-site"
PIDFILE="$PROJECTDIR/gunicorn-rc.pid"
SERVER_ARGS="--workers=2 --daemon --bind=$ADDRESS -p $PIDFILE"
RUN_CMD="gunicorn_django $SERVER_ARGS"

case "$1" in
'start')
  if [ -f $PIDFILE ]; then
    if [ "$(ps -p `cat $PIDFILE` | wc -l)" -gt 1]; then
      echo "Gunicorn server already running"
      stat_fail
      exit 1
    fi
  fi
  cd $PROJECTDIR
  stat_busy "Starting Gunicorn server"
  $RUN_CMD
  stat_done
  ;;
'stop')
  if [ -f $PIDFILE ] && [ "$(ps -p `cat $PIDFILE` | wc -l)" -gt 1 ]; then
    stat_busy "Stopping Gunicorn server"
    kill -9 `cat $PIDFILE`
    rm $PIDFILE
    stat_done
  else
    if [ -f $PIDFILE ]; then
      echo "Gunicorn server not running"
    else
      echo "No pid file for Gunicorn server"
    fi
    stat_fail
    exit 1
  fi
  ;;
'restart')
  $0 stop
  sleep 10
  $0 start
  ;;  
*)
  echo "Usage: $0 { start | stop | restart }"
  ;;
esac

exit 0
